<?php

namespace App\Http\Controllers\api\posts;

use App\Http\Controllers\api\base\BaseController;
use App\Http\Requests\base\IdRequest;
use App\Http\Requests\posts\CommentRequest;
use App\Http\Requests\posts\PostsRequest;
use App\Http\Resources\posts\FansPageCollection;
use App\Http\Resources\posts\FollowsPageCollection;
use App\Http\Resources\posts\PostsCommentPageCollection;
use App\Http\Resources\posts\PostsPageCollection;
use App\Http\Resources\posts\PostsResource;
use App\Models\config\Config;
use App\Models\goods\Order;
use App\Models\goods\OrderDetail;
use App\Models\posts\Posts;
use App\Models\posts\PostsCate;
use App\Models\posts\PostsCollection;
use App\Models\posts\PostsComment;
use App\Models\posts\PostsUp;
use App\Models\posts\UserFollow;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends BaseController
{

    public function cate(Request $request)
    {
        $map['status'] = 1;
        
        if ($request->type){
            $map['type'] = $request->type;
        }

        return success( PostsCate::where($map)->select(['id','name'])->orderBy('sort')->get() );
    }

    public function publish(PostsRequest $request)
    {

        $params = $request->all();
        $params['user_id'] = $this->user_id;
        if ($this->user->is_system == 1){
            $params['is_system'] = 1;
        }else{
            $params['is_system'] = 0;
        }
        $result = Posts::create($params);

        if ($result){

            if ($params['goods_id']){
                $map['user_id']  = $this->user_id;
                $map['goods_id'] = $params['goods_id'];
                $count = Posts::where($map)->count();
                if ($count == 1){//第一次发布该商品
                    $order = OrderDetail::where([
                        'status' => 3,
                        'user_id' => $this->user_id,
                        'goods_id' => $params['goods_id']
                    ])
                        ->latest()
                        ->first();
                    if ($order){
                        $coin = bcmul($order->total_price,Config::getConfig('posts_published_ratio'.$params['type']),2);
                        if ($coin >= 0.01){
                            if ($params['type'] == 1){
                                $str = "咨询";
                            }else{
                                $str = "视频";
                            }
                            moneyDetailAdd($this->user_id,$coin,"发布购买体验{$str}");
                            User::whereId($this->user_id)->increment('money',$coin);
                            return successWithMsg("发布购买体验{$str}成功,奖励[{$coin}]");
                        }
                    }

                }
            }

            return successWithMsg("提交成功");
        }
        return error();
    }


    /**
     * 列表
     */
    public function lists(Request $request)
    {
        $map = [];
        $add = [];
        $sql = new Posts();

        if (is_numeric($request->type)){
            $map['type'] = $request->type;
            $m['type'] = $request->type;
        }

        if (is_numeric($request->posts_cate_id)){
            $map['posts_cate_id'] = $request->posts_cate_id;
        }

        if (is_numeric($request->user_id)){
            $map['user_id'] = $request->user_id;
        }

        if ($request->get_my == 1){//获取自己的
            $map['user_id'] = $this->user_id;
        }else{
            if (!isset($map['user_id'])){ // 未筛选用户的列表  增加系统用户填写信息
                $map['is_show'] = 1;
                $m['is_show'] = 1;
                $m['is_system'] = 1;

                $add = Posts::where($m)->first();
            }

        }

        if (!empty($request->keyword)){
            $map[] = ['title','like',"%{$request->keyword}%"];
        }

        if ($request->get_up == 1){
            $ids = PostsUp::where(['user_id'=>$this->user_id,'status'=>1])
                ->pluck('posts_id');
            if ($ids->isNotEmpty()){
                $ids = $ids->toArray();
            }else{
                $ids = [];
            }
            $sql = $sql->whereIn('id',$ids);
        }

        if ($request->get_collection == 1){
            $ids = PostsCollection::where(['user_id'=>$this->user_id,'status'=>1])
                ->pluck('posts_id');
            if ($ids->isNotEmpty()){
                $ids = $ids->toArray();
            }else{
                $ids = [];
            }
            $sql = $sql->whereIn('id',$ids);
        }

        if ($request->get_follow == 1){
            $ids = UserFollow::where(['user_id'=>$this->user_id,'status'=>1])
                ->pluck('follow_id');
            if ($ids->isNotEmpty()){
                $ids = $ids->toArray();
            }else{
                $ids = [];
            }
            $sql = $sql->whereIn('user_id',$ids);
        }

        $rows = $sql->where($map)
            ->with('user','goods','posts_cate')
            ->with(['up'=>function ($query){
                $query->where('user_id',$this->user_id);
            }])
            ->with(['collection'=>function ($query){
                $query->where('user_id',$this->user_id);
            }])
            ->with(['follow'=>function ($query){
                $query->where('user_id',$this->user_id);
            }])
            ->latest()
            ->paginate();


        return success( new PostsPageCollection( $rows ,$add) );

    }

    public function detail(IdRequest $request)
    {
        $posts = Posts::findOrFail($request->id);
        return success( new PostsResource($posts));
    }



    public function comment(CommentRequest $request)
    {

        $this->ApiLimit(2,$this->user_id);

        $params = $request->all();
        $params['user_id'] = $this->user_id;

        DB::beginTransaction();
        try {
            PostsComment::create($params);
            Posts::whereId($request->posts_id)->increment('comment_num');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());
        }

        return successWithMsg("提交成功");
    }

    public function comments(IdRequest $request)
    {
        $map['posts_id'] = $request->id;

        $rows = PostsComment::where($map)->with('user')->paginate();

        return success(  new PostsCommentPageCollection( $rows ));
    }

    public function up(IdRequest $request)
    {

        $map['user_id'] = $this->user_id;
        $map['posts_id'] = $request->id;

        $up = PostsUp::firstOrNew($map);

        $posts = Posts::findOrFail($request->id);
        if ($posts instanceof Posts);

        DB::beginTransaction();
        try {

            if ($up->id){
                $isCreate = false;
                if ($up->status == 1){
                    $up->status = 0;
                }else{
                    $up->status = 1;
                }
            }else{
                $isCreate = true;
                $up->status = 1;
            }

            if ($up->status == 1){
                $posts->increment('up_num');
            }else{
                $posts->decrement('up_num');
            }

            $up->save();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());
        }
        if ($isCreate && $this->user_id != $posts->user_id){//第一次点赞
//            发布的咨询被点赞奖励  发布的视频被点赞奖励
            $coin = Config::getConfig('posts_upd'.$posts->type);
            if ($coin >= 0.01){
                if ($posts->type == 1){
                    $str = "咨询";
                }else{
                    $str = "视频";
                }
                moneyDetailAdd($posts->user_id,$coin,"发布的{$str}被点赞");
                User::whereId($posts->user_id)->increment('money',$coin);
            }

        }

        return successWithMsg("提交成功");
    }

    public function follow(IdRequest $request)
    {

        if ($request->id == $this->user_id){
            return error("不能关注自己!");
        }

        $map['user_id'] = $this->user_id;
        $map['follow_id'] = $request->id;

        $follow = UserFollow::firstOrNew($map);

        if ($follow->status == 1){
            $follow->status = 0;
        }else{
            $follow->status = 1;
        }

        $result = $follow->save();

        if ($result){
            return successWithMsg("操作成功");
        }

        return error();

    }


    public function follows(Request $request)
    {
        if (isInt($request->user_id)){
            $map['user_id'] = $request->user_id;
        }else{
            $map['user_id'] = $this->user_id;
        }

        $map['status']  = 1;
        $rows = UserFollow::where($map)->whereHas('follow', function ($query) {
            $query->where('user_id', '!=', '0');
        })->with('follow')->paginate();
        return success( new FollowsPageCollection( $rows ));
    }


    public function fans(Request $request)
    {
        if (isInt($request->user_id)){
            $map['follow_id'] = $request->user_id;
        }else{
            $map['follow_id'] = $this->user_id;
        }

        $map['status']  = 1;
        $rows = UserFollow::where($map)->whereHas('user', function ($query) {
            $query->where('user_id', '!=', '0');
        })->with('user')->paginate();
        return success( new FansPageCollection( $rows ));
    }

    /**
     * 帖子收藏  取消收藏
     * @param IdRequest $request
     * @return mixed
     * @throws \Exception
     */
    public function collection(IdRequest $request)
    {

        $map['user_id'] = $this->user_id;
        $map['posts_id'] = $request->id;

        $collection = PostsCollection::firstOrNew($map);

        $posts = Posts::findOrFail($request->id);
        if ($posts instanceof Posts);

        DB::beginTransaction();
        try {

            if ($collection->id){
                $isCreate = false;
                if ($collection->status == 1){
                    $collection->status = 0;
                }else{
                    $collection->status = 1;
                }
            }else{
                $isCreate = true;
                $collection->status = 1;
            }

            if ($collection->status == 1){
                $posts->increment('collection_num');
            }else{
                $posts->decrement('collection_num');
            }

            $collection->save();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());
        }
        if ($isCreate && $this->user_id != $posts->user_id){//第一次点赞
//            发布的咨询被点赞奖励  发布的视频被点赞奖励
            $coin = Config::getConfig('posts_collection'.$posts->type);
            if ($coin >= 0.01){
                if ($posts->type == 1){
                    $str = "咨询";
                }else{
                    $str = "视频";
                }
                moneyDetailAdd($posts->user_id,$coin,"发布的{$str}被收藏");
                User::whereId($posts->user_id)->increment('money',$coin);
            }

        }

        return successWithMsg("提交成功");
    }



    public function shareCallback(IdRequest $request)
    {
        $post = Posts::findOrFail($request->id);
        $post->increment('share_num');
        return successWithMsg("操作成功");
    }



    /**
     * 我的已购商品列表
     */
    public function myGoods()
    {
        $map['user_id'] = $this->user_id;
        $goods = OrderDetail::where($map)->whereHas('goods', function ($query) {
            $where['status'] = 1;
            $query->where($where);
        })->with('goods')->groupBy('goods_id')->get();
        $rows = [];
        foreach ($goods as $value){
            $rows[] = [
                'id' => $value->goods->id,
                'name' => $value->goods->name,
            ];
        }
        return success( $rows );
    }

    /**
     * 帖子删除
     */
    public function del(IdRequest $request)
    {
        $map['user_id'] = $this->user_id;
        $map['id'] = $request->id;
        $result = Posts::where($map)->delete();
        if ($result){
            return successWithMsg("删除成功");
        }
        return error();
    }


















}
